from django import forms
from django.forms import inlineformset_factory
from django.shortcuts import render, redirect, get_object_or_404
from django.core.paginator import Paginator
from django.urls import reverse
from myadmin.models import DietPlan, DietPlanDetail, DietPlanForm, Users, Foods
from django.http import HttpResponseRedirect


def index(request, pIndex=1):
    """浏览饮食计划（包含创建时间和更新时间）"""
    # 获取搜索关键词
    search_keyword = request.GET.get('search', '').strip()
    
    # 基础查询集
    plan_list = DietPlan.objects.all()
    
    # 如果有搜索关键词，添加过滤条件
    if search_keyword:
        plan_list = plan_list.filter(
            plan_name__icontains=search_keyword  # 搜索计划名称
        ) | plan_list.filter(
            user__username__icontains=search_keyword  # 搜索关联用户名
        ) | plan_list.filter(
            notes__icontains=search_keyword  # 搜索备注
        )
    
    # 按创建时间倒序
    plan_list = plan_list.order_by('-created_at')
    
    # 分页处理
    p = Paginator(plan_list, 5)  # 每页5条数据
    if pIndex < 1:
        pIndex = 1
    if pIndex > p.num_pages:
        pIndex = p.num_pages
    plan_list = p.page(pIndex)
    
    # 上下文包含所有计划数据和搜索关键词
    context = {
        'plan_list': plan_list,
        'pIndex': pIndex,
        'total_pages': p.num_pages,
        'search_keyword': search_keyword  # 传递搜索关键词用于回显
    }
    return render(request, 'myadmin/dietplan/index.html', context)


# 以下其他函数保持不变
def add(request):
    """加载添加饮食计划表单"""
    users = Users.objects.filter(status__in=[1, 6])  # 只显示正常和管理员用户
    context = {
        'users': users,
        'foods': Foods.objects.all().order_by('food_name'),
        'meal_type_choices': DietPlanDetail.MEAL_TYPE_CHOICES  # 传递餐次类型选项
    }
    return render(request, 'myadmin/dietplan/add.html', context)


def insert(request):
    """执行添加饮食计划"""
    try:
        # 获取表单数据
        plan_name = request.POST.get('plan_name').strip()
        user_id = request.POST.get('user_id')
        target_calories = request.POST.get('target_calories')
        protein_target = request.POST.get('protein_target')
        carbs_target = request.POST.get('carbs_target')
        fat_target = request.POST.get('fat_target')
        notes = request.POST.get('notes', '').strip()
        
        # 验证数据
        if not plan_name:
            context = {'info': '计划名称不能为空！'}
            return render(request, 'myadmin/info.html', context)
            
        # 获取用户对象
        user = get_object_or_404(Users, user_id=user_id)
        
        # 创建饮食计划（创建时会自动生成created_at和updated_at）
        plan = DietPlan()
        plan.plan_name = plan_name
        plan.user = user
        plan.is_active = True  # 默认激活
        plan.target_calories = int(target_calories) if target_calories else None
        plan.protein_target = float(protein_target) if protein_target else None
        plan.carbs_target = float(carbs_target) if carbs_target else None
        plan.fat_target = float(fat_target) if fat_target else None
        plan.notes = notes
        plan.save()  # 保存时自动设置created_at和updated_at
        
        context = {'info': '添加饮食计划成功！'}
    except Exception as e:
        context = {'info': f'添加饮食计划失败：{str(e)}'}
    return render(request, 'myadmin/info.html', context)


def detail(request, plan_id):
    """查看饮食计划详情"""
    plan = get_object_or_404(DietPlan, plan_id=plan_id)
    details = DietPlanDetail.objects.filter(plan=plan).order_by('meal_type')
    context = {
        'plan': plan,
        'details': details
    }
    return render(request, 'myadmin/dietplan/detail.html', context)


def edit(request, plan_id):
    """加载编辑饮食计划表单"""
    plan = get_object_or_404(DietPlan, plan_id=plan_id)
    users = Users.objects.filter(status__in=[1, 6])
    DietPlanDetailFormSet = inlineformset_factory(
        DietPlan, DietPlanDetail,
        fields=['meal_type', 'food', 'quantity','meal_time', 'notes'],
        extra=0  # 不额外显示空表单，只显示已有数据
    )
    if request.method == 'POST':
        plan_form = DietPlanForm(request.POST, instance=plan)
        detail_formset = DietPlanDetailFormSet(request.POST, instance=plan)
        if plan_form.is_valid() and detail_formset.is_valid():
            plan = plan_form.save()
            detail_formset.save()
            return redirect('myadmin_dietplan_index')
    else:
        plan_form = DietPlanForm(instance=plan)
        detail_formset = DietPlanDetailFormSet(instance=plan)
    foods = Foods.objects.all().order_by('food_name')
    context = {
        'plan': plan,
        'users': users,
        'plan_form': plan_form,
        'detail_formset': detail_formset,
        'foods': foods
    }
    return render(request,'myadmin/dietplan/edit.html', context)


def update(request, plan_id):
    """执行编辑饮食计划（修复用户验证问题）"""
    try:
        plan = get_object_or_404(DietPlan, plan_id=plan_id)
        
        # 获取表单数据
        plan_name = request.POST.get('plan_name').strip()
        # 关键修复：从表单获取user_id时增加默认值，避免空值
        user_id = request.POST.get('user_id', plan.user.user_id)  # 默认为当前计划的用户ID
        target_calories = request.POST.get('target_calories')
        protein_target = request.POST.get('protein_target')
        carbs_target = request.POST.get('carbs_target')
        fat_target = request.POST.get('fat_target')
        notes = request.POST.get('notes', '').strip()
        is_active = request.POST.get('is_active', '0') == '1'
        
        # 验证核心数据
        if not plan_name:
            context = {'info': '计划名称不能为空！'}
            return render(request, 'myadmin/info.html', context)
        
        # 修复用户查询逻辑：增加异常捕获，避免用户不存在时崩溃
        try:
            user = Users.objects.get(user_id=user_id)
        except Users.DoesNotExist:
            # 用户不存在时，使用计划原有的用户
            user = plan.user
            context = {'info': f'用户ID {user_id} 不存在，已保留原用户'}
            return render(request, 'myadmin/info.html', context)
        
        # 更新字段
        plan.plan_name = plan_name
        plan.user = user
        plan.is_active = is_active
        # 数值类型转换增加容错处理
        plan.target_calories = int(target_calories) if target_calories and target_calories.isdigit() else None
        plan.protein_target = float(protein_target) if protein_target else None
        plan.carbs_target = float(carbs_target) if carbs_target else None
        plan.fat_target = float(fat_target) if fat_target else None
        plan.notes = notes
        plan.save()  # 保存时自动更新updated_at
        
        context = {'info': '更新饮食计划成功！'}
    except Exception as e:
        context = {'info': f'更新饮食计划失败：{str(e)}'}
    return render(request, 'myadmin/info.html', context)


def delete(request, plan_id):
    """删除饮食计划"""
    try:
        plan = get_object_or_404(DietPlan, plan_id=plan_id)
        plan.delete()
        return HttpResponseRedirect(reverse('myadmin_dietplan_index', args=[1]))
    except Exception as e:
        context = {'info': f'删除饮食计划失败：{str(e)}'}
        return render(request, 'myadmin/info.html', context)


# 饮食计划详情项相关操作（保持不变）
def detail_add(request, plan_id):
    plan = get_object_or_404(DietPlan, plan_id=plan_id)
    foods = Foods.objects.all().order_by('food_name')
    context = {
        'plan': plan,
        'foods': foods
    }
    return render(request, 'myadmin/dietplan/detail_add.html', context)


def detail_insert(request, plan_id):
    try:
        plan = get_object_or_404(DietPlan, plan_id=plan_id)
        
        meal_type = request.POST.get('meal_type')
        food_id = request.POST.get('food_id')
        quantity = request.POST.get('quantity')
        meal_time = request.POST.get('meal_time')
        notes = request.POST.get('notes', '').strip()
        
        if not all([meal_type, food_id, quantity]):
            context = {'info': '餐次类型、食物和数量不能为空！'}
            return render(request, 'myadmin/info.html', context)
            
        detail = DietPlanDetail()
        detail.plan = plan
        detail.meal_type = meal_type
        detail.food = get_object_or_404(Foods, food_id=food_id)
        detail.quantity = float(quantity)
        detail.meal_time = meal_time if meal_time else None
        detail.notes = notes
        detail.save()
        
        return HttpResponseRedirect(reverse('myadmin_dietplan_detail', args=[plan_id]))
    except Exception as e:
        context = {'info': f'添加详情项失败：{str(e)}'}
        return render(request, 'myadmin/info.html', context)


def detail_edit(request, detail_id):
    detail = get_object_or_404(DietPlanDetail, detail_id=detail_id)
    foods = Foods.objects.all().order_by('food_name')
    context = {
        'detail': detail,
        'foods': foods
    }
    return render(request, 'myadmin/dietplan/detail_edit.html', context)


def detail_update(request, detail_id):
    try:
        detail = get_object_or_404(DietPlanDetail, detail_id=detail_id)
        
        meal_type = request.POST.get('meal_type')
        food_id = request.POST.get('food_id')
        quantity = request.POST.get('quantity')
        meal_time = request.POST.get('meal_time')
        notes = request.POST.get('notes', '').strip()
        
        if not all([meal_type, food_id, quantity]):
            context = {'info': '餐次类型、食物和数量不能为空！'}
            return render(request, 'myadmin/info.html', context)
            
        detail.meal_type = meal_type
        detail.food = get_object_or_404(Foods, food_id=food_id)
        detail.quantity = float(quantity)
        detail.meal_time = meal_time if meal_time else None
        detail.notes = notes
        detail.save()
        
        return HttpResponseRedirect(reverse('myadmin_dietplan_detail', args=[detail.plan.plan_id]))
    except Exception as e:
        context = {'info': f'更新详情项失败：{str(e)}'}
        return render(request, 'myadmin/info.html', context)


def detail_delete(request, detail_id):
    try:
        detail = get_object_or_404(DietPlanDetail, detail_id=detail_id)
        plan_id = detail.plan.plan_id
        detail.delete()
        return HttpResponseRedirect(reverse('myadmin_dietplan_detail', args=[plan_id]))
    except Exception as e:
        context = {'info': f'删除详情项失败：{str(e)}'}
        return render(request, 'myadmin/info.html', context)
